<template>
  <div class="order-detail" v-loading="loading">
    <!-- 订单状态 -->
    <div class="status-card">
      <div class="status-header">
        <div class="order-no">订单号：{{ order.orderNo }}</div>
        <el-tag :type="getStatusType(order.status)">
          {{ getStatusLabel(order.status) }}
        </el-tag>
      </div>
      <div class="status-timeline">
        <el-steps :active="getStatusStep(order.status)" finish-status="success">
          <el-step title="提交订单" description=""></el-step>
          <el-step title="付款成功" description=""></el-step>
          <el-step title="商品发货" description=""></el-step>
          <el-step title="交易完成" description=""></el-step>
        </el-steps>
      </div>
    </div>

    <!-- 收货信息 -->
    <el-card class="info-card">
      <div slot="header">
        <span>收货信息</span>
      </div>
      <div class="info-content" v-loading="addressLoading">
        <div v-if="!addressInfo.id && !addressLoading" class="empty-info">
          暂无收货地址信息
        </div>
        <template v-else>
          <div class="info-item">
            <span class="label">收货人：</span>
            <span>{{ addressInfo.receiverName || '暂无信息' }}</span>
          </div>
          <div class="info-item">
            <span class="label">联系电话：</span>
            <span>{{ addressInfo.receiverPhone || '暂无信息' }}</span>
          </div>
          <div class="info-item">
            <span class="label">收货地址：</span>
            <span>{{ formatAddress(addressInfo) || '暂无信息' }}</span>
          </div>
        </template>
      </div>
    </el-card>

    <!-- 商品信息 -->
    <el-card class="info-card">
      <div slot="header">
        <span>商品信息</span>
      </div>
      <div class="product-list">
        <div v-for="(item, index) in order.orderItems" :key="index" class="product-item">
          <el-image
            :src="getProductImage(item)"
            :preview-src-list="[getProductImage(item)]"
            class="product-image">
          </el-image>
          <div class="product-info">
            <div class="product-name">{{ getProductName(item, index) }}</div>
            <div class="product-price">
              <span class="price">¥{{ item.price || 0 }}</span>
              <span class="quantity">× {{ item.quantity || 0 }}</span>
            </div>
          </div>
          <div class="product-total">
            ¥{{ ((item.price || 0) * (item.quantity || 0)).toFixed(2) }}
          </div>
        </div>
      </div>
      <div class="order-total">
        <div class="total-item">
          <span>商品总价：</span>
          <span class="price">¥{{ order.totalAmount || '0.00' }}</span>
        </div>
        <div class="total-item">
          <span>运费：</span>
          <span class="price">¥{{ order.shippingFee || '0.00' }}</span>
        </div>
        <div class="total-item">
          <span>实付金额：</span>
          <span class="price highlight">¥{{ order.totalAmount || '0.00' }}</span>
        </div>
        <div class="total-item" v-if="order.remark">
          <span>订单备注：</span>
          <span>{{ order.remark }}</span>
        </div>
        <div class="total-item">
          <span>支付方式：</span>
          <span>{{ formatPaymentMethod(order.paymentMethod) }}</span>
        </div>
      </div>
    </el-card>

    <!-- 订单信息 -->
    <el-card class="info-card">
      <div slot="header">
        <span>订单信息</span>
      </div>
      <div class="info-content">
        <div class="info-item">
          <span class="label">订单编号：</span>
          <span>{{ order.orderNo || '暂无信息' }}</span>
        </div>
        <div class="info-item">
          <span class="label">创建时间：</span>
          <span>{{ formatDateTime(order.createdTime) }}</span>
        </div>
        <div class="info-item">
          <span class="label">更新时间：</span>
          <span>{{ formatDateTime(order.updatedTime) }}</span>
        </div>
      </div>
    </el-card>

    <!-- 操作按钮 -->
    <div class="operation-bar">
      <el-button @click="$router.push('/main/shop/orders')">返回列表</el-button>
      <template v-if="order.status === 'pending'">
        <el-button type="success" @click="handlePay">立即付款</el-button>
        <el-button type="danger" @click="handleCancel">取消订单</el-button>
      </template>
      <el-button
        v-if="order.status === 'shipped'"
        type="success"
        @click="handleConfirmReceive">
        确认收货
      </el-button>
      <el-button
        v-if="['completed', 'cancelled'].includes(order.status)"
        type="danger"
        @click="handleDelete">
        删除订单
      </el-button>
    </div>
  </div>
</template>

<script>
import { mapState, mapActions } from 'vuex'
import { getOrderDetail, payOrder, confirmReceive } from '@/api/order'
import { getAddressDetail } from '@/api/user'

export default {
  name: 'OrderDetail',
  data() {
    return {
      loading: false,
      addressLoading: false,
      order: {
        id: '',
        orderNo: '',
        status: '',
        addressId: null,
        paymentMethod: '',
        remark: '',
        orderItems: [],
        totalAmount: 0,
        shippingFee: 0,
        createdTime: '',
        updatedTime: ''
      },
      addressInfo: {
        id: null,
        receiverName: '',
        receiverPhone: '',
        province: '',
        city: '',
        district: '',
        detailAddress: '',
        isDefault: false
      },
      statusOptions: [
        { value: 'PENDING', label: '待付款' },
        { value: 'PAID', label: '已付款' },
        { value: 'SHIPPED', label: '已发货' },
        { value: 'COMPLETED', label: '已完成' },
        { value: 'CANCELLED', label: '已取消' }
      ]
    }
  },
  computed: {
    orderId() {
      return this.$route.params.id
    }
  },
  created() {
    this.fetchOrderDetail()
  },
  methods: {
    ...mapActions('order', ['cancelOrder', 'deleteOrder']),

    async fetchOrderDetail() {
      try {
        this.loading = true
        const response = await getOrderDetail(this.orderId)
        console.log('订单详情:', response)
        
        if (response.code === 200) {
          this.order = response.data
          
          // 处理订单项数据
          if (!this.order.orderItems && this.order.items) {
            this.order.orderItems = this.order.items
          }
          
          // 如果有地址ID，获取地址详情
          if (this.order.addressId) {
            this.fetchAddressDetail(this.order.addressId)
          }
        } else {
          this.$message.error(response.message || '获取订单详情失败')
        }
      } catch (error) {
        console.error('获取订单详情错误:', error)
        this.$message.error('获取订单详情失败')
      } finally {
        this.loading = false
      }
    },
    
    async fetchAddressDetail(addressId) {
      try {
        this.addressLoading = true
        const response = await getAddressDetail(addressId)
        if (response.code === 200) {
          this.addressInfo = response.data
        } else {
          console.error('获取地址详情失败:', response.message)
          this.$message.warning('获取收货地址信息失败')
        }
      } catch (error) {
        console.error('获取地址详情错误:', error)
        this.$message.warning('获取收货地址信息失败')
      } finally {
        this.addressLoading = false
      }
    },

    getStatusType(status) {
      // 处理大写状态码
      const statusVal = typeof status === 'string' ? status.toLowerCase() : status
      
      const statusMap = {
        'pending': 'warning',
        'paid': 'primary',
        'shipped': 'info',
        'completed': 'success',
        'cancelled': 'danger'
      }
      return statusMap[statusVal] || 'info'
    },

    getStatusLabel(status) {
      // 处理大写状态码
      const statusVal = typeof status === 'string' ? status.toUpperCase() : status
      
      const statusLabels = {
        'PENDING': '待付款',
        'PAID': '已付款',
        'SHIPPED': '已发货',
        'COMPLETED': '已完成',
        'CANCELLED': '已取消'
      }
      
      return statusLabels[statusVal] || `未知状态(${status})`
    },

    getStatusStep(status) {
      // 处理大写状态码
      const statusVal = typeof status === 'string' ? status.toUpperCase() : status
      
      const stepMap = {
        'PENDING': 1,
        'PAID': 2,
        'SHIPPED': 3,
        'COMPLETED': 4,
        'CANCELLED': 0
      }
      return stepMap[statusVal] || 0
    },

    async handlePay() {
      try {
        await this.$confirm('确认支付该订单吗？', '提示', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        await payOrder(this.orderId, 'alipay') // 默认使用支付宝支付
        this.$message.success('支付成功')
        this.fetchOrderDetail()
      } catch (error) {
        if (error !== 'cancel') {
          console.error('支付失败:', error)
          this.$message.error('支付失败')
        }
      }
    },

    async handleCancel() {
      try {
        await this.$confirm('确认取消该订单吗？', '提示', {
          type: 'warning'
        })
        await this.cancelOrder(this.orderId)
        this.$message.success('订单已取消')
        this.fetchOrderDetail()
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error('取消订单失败')
        }
      }
    },

    async handleConfirmReceive() {
      try {
        await this.$confirm('确认已收到商品吗？', '提示', {
          type: 'warning'
        })
        await confirmReceive(this.orderId)
        this.$message.success('确认收货成功')
        this.fetchOrderDetail()
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error('确认收货失败')
        }
      }
    },

    async handleDelete() {
      try {
        await this.$confirm('确认删除该订单吗？删除后不可恢复', '提示', {
          type: 'warning'
        })
        await this.deleteOrder(this.orderId)
        this.$message.success('删除成功')
        this.$router.push('/main/shop/orders')
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error('删除失败')
        }
      }
    },

    formatAddress(address) {
      if (!address) return '暂无地址信息'
      
      const parts = []
      if (address.province) parts.push(address.province)
      if (address.city) parts.push(address.city)
      if (address.district) parts.push(address.district)
      if (address.detailAddress) parts.push(address.detailAddress)
      
      if (parts.length > 0) {
        return parts.join(' ')
      } else if (address.receiverAddress) {
        return address.receiverAddress
      }
      
      return '暂无地址信息'
    },

    formatPaymentMethod(method) {
      if (!method) return '未知支付方式'
      
      const methodMap = {
        'alipay': '支付宝',
        'wechat': '微信支付',
        'creditcard': '信用卡',
        'cod': '货到付款'
      }
      
      return methodMap[method.toLowerCase()] || method
    },

    formatDateTime(timestamp) {
      if (!timestamp) return '暂无数据'
      
      let date
      try {
        // 尝试将字符串转换为Date对象
        if (typeof timestamp === 'string') {
          // 处理后端返回的标准格式 (2023-03-30T19:32:58)
          if (timestamp.includes('T')) {
            date = new Date(timestamp)
          } else {
            // 处理可能的其他格式 (2023-03-30 19:32:58)
            date = new Date(timestamp.replace(/-/g, '/'))
          }
        } else if (timestamp instanceof Date) {
          date = timestamp
        } else {
          // 假设是时间戳（毫秒）
          date = new Date(Number(timestamp))
        }
        
        // 检查日期是否有效
        if (isNaN(date.getTime())) {
          return timestamp // 如果转换失败，返回原始字符串
        }
        
        // 格式化为 YYYY-MM-DD HH:mm:ss
        const year = date.getFullYear()
        const month = String(date.getMonth() + 1).padStart(2, '0')
        const day = String(date.getDate()).padStart(2, '0')
        const hours = String(date.getHours()).padStart(2, '0')
        const minutes = String(date.getMinutes()).padStart(2, '0')
        const seconds = String(date.getSeconds()).padStart(2, '0')
        
        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
      } catch (error) {
        console.error('日期格式化错误:', error)
        return timestamp // 返回原始值
      }
    },

    getProductImage(item) {
      // 获取商品图片URL
      let imageUrl = item.imageUrl || item.productImage || null;
      
      if (!imageUrl) {
        return require('@/assets/default.jpg');
      }
      
      // 服务器地址
      const serverUrl = 'http://localhost:8080'; // 后端API服务器地址
      
      // 如果路径已经是完整URL，直接返回
      if (imageUrl.startsWith('http://') || imageUrl.startsWith('https://')) {
        return imageUrl;
      }
      
      // 确保路径以 / 开头
      if (!imageUrl.startsWith('/')) {
        imageUrl = '/' + imageUrl;
      }
      
      // 构建完整URL
      return serverUrl + imageUrl;
    },

    getProductName(item, index) {
      return item.name || item.productName || `商品${index + 1}`
    }
  }
}
</script>

<style lang="scss" scoped>
.order-detail {
  padding: 20px;
  
  .status-card {
    padding: 20px;
    margin-bottom: 20px;
    background-color: #fff;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    
    .status-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;
      
      .order-no {
        font-size: 16px;
        color: #303133;
      }
    }
    
    .status-timeline {
      padding: 0 20px;
    }
  }
  
  .info-card {
    margin-bottom: 20px;
    
    .empty-info {
      color: #909399;
      text-align: center;
      padding: 20px 0;
    }
    
    .info-content {
      .info-item {
        margin-bottom: 10px;
        
        &:last-child {
          margin-bottom: 0;
        }
        
        .label {
          color: #606266;
          margin-right: 10px;
        }
      }
    }
    
    .product-list {
      .product-item {
        display: flex;
        align-items: center;
        padding: 15px 0;
        border-bottom: 1px solid #eee;
        
        &:last-child {
          border-bottom: none;
        }
        
        .product-image {
          width: 80px;
          height: 80px;
          margin-right: 15px;
          object-fit: cover;
        }
        
        .product-info {
          flex: 1;
          
          .product-name {
            font-size: 14px;
            color: #303133;
            margin-bottom: 5px;
          }
          
          .product-price {
            color: #909399;
            
            .price {
              color: #f56c6c;
            }
            
            .quantity {
              margin-left: 5px;
            }
          }
        }
        
        .product-total {
          font-weight: bold;
          color: #f56c6c;
          width: 100px;
          text-align: right;
        }
      }
    }
    
    .order-total {
      border-top: 1px solid #eee;
      padding-top: 15px;
      margin-top: 10px;
      
      .total-item {
        display: flex;
        justify-content: flex-end;
        margin-bottom: 5px;
        
        .price {
          min-width: 100px;
          text-align: right;
          
          &.highlight {
            color: #f56c6c;
            font-size: 18px;
            font-weight: bold;
          }
        }
      }
    }
  }
  
  .operation-bar {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
    margin-top: 20px;
  }
}
</style> 